// backend/functions/letters.js
const AV = require('leancloud-storage');

AV.Cloud.define('fetchRandomLetter', async (request) => {
  const { userId } = request.params;
  if (!userId) {
    throw new AV.Cloud.Error('请提供用户ID。', { code: 400 });
  }

  const query = new AV.Query('Letter');
  query.equalTo('status', 'queued');
  query.equalTo('is_public', true);
  query.lessThanOrEqualTo('deliver_at', new Date());
  query.notEqualTo('user_id', userId);

  const count = await query.count();
  if (count === 0) {
    return null;
  }

  const randomIndex = Math.floor(Math.random() * count);
  query.skip(randomIndex);
  query.limit(1);

  const letter = await query.first();

  if (letter) {
    letter.set('status', 'delivered');
    letter.set('recipient_id', userId);
    await letter.save();
    console.log(`信件 ${letter.id} 已成功分配给用户 ${userId}`);
    return letter;
  } else {
    return null;
  }
});
